using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace FinData.Services
{
    public class MongoService
    {
        private readonly IMongoDatabase _database;
        private readonly MongoClient _client;

        public MongoService()
        {
            // 配置MongoDB连接，优先使用环境变量
            var connectionString = Environment.GetEnvironmentVariable("MongoDbSettings__ConnectionString");
            var databaseName = Environment.GetEnvironmentVariable("MongoDbSettings__DatabaseName");
            
            string mongoConnectionString = string.IsNullOrEmpty(connectionString) 
                ? "mongodb://panda:panda@127.0.0.1:27017/admin"
                : connectionString;
                
            string mongoDatabaseName = string.IsNullOrEmpty(databaseName)
                ? "panda"
                : databaseName;
            
            Console.WriteLine($"使用MongoDB连接: {mongoConnectionString}, 数据库: {mongoDatabaseName}");
            
            _client = new MongoClient(mongoConnectionString);
            _database = _client.GetDatabase(mongoDatabaseName);
        }
        
        /// <summary>
        /// 测试MongoDB连接
        /// </summary>
        /// <returns>连接成功返回true，否则返回false</returns>
        public async Task<bool> TestConnectionAsync()
        {
            try
            {
                await _database.RunCommandAsync((Command<BsonDocument>)"{ping:1}");
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"MongoDB连接测试失败: {ex.Message}");
                return false;
            }
        }
    }
} 